import React, { useState } from "react";
import styles from "./index.module.less";
import Nav from "@pages/nav";
import PortalContainer from "@components/portalContainer";
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";
import actualGmoney from "@utils/actualGmoney";
// import AvatarEditor from 'react-avatar-editor'
import toast from "@utils/showToast";
import { connect } from "react-redux";
import { onSellGoodsAction } from "@redux/actions";
import { useNavigate } from "react-router-dom";

const moneyReg =
    /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

const Sell = (props) => {
    const navigate = useNavigate();
    const { onSellGoodsAction } = props;

    const [md, setMd] = useState("");
    const [goodsName, setGoodsName] = useState("");
    const [cateTag, setCateTag] = useState("");
    const [brand, setBrand] = useState("");
    const [oldDegree, setOldDegree] = useState("");
    const [price, setPrice] = useState("");
    const [actualMoney, setActualMoney] = useState(0);
    const [isAcceptCutPrice, setIsAcceptCutPrice] = useState(true);
    const [billImg, setBillImg] = useState("");
    const [imgArr, setImgArr] = useState([]);

    const putOnSale = () => {
        if (!goodsName.trim()) {
            toast.fail("请填写商品名称!");
            return;
        }
        if (!cateTag) {
            toast.fail("请放入1-5张商品图片!");
            return;
        }
        if (!brand) {
            toast.fail("请标明品牌!");
            return;
        }
        if (
            parseInt(oldDegree) !== parseFloat(oldDegree) ||
            parseInt(oldDegree) > 10 ||
            parseInt(oldDegree) <= 0
        ) {
            toast.fail("成色必须是1-10之间的整数！");
            return;
        }
        if (!price) {
            toast.fail("请明码标价!");
            return;
        }
        if (!billImg || !billImg.includes("http")) {
            toast.fail("请放入发票图片链接!");
            return;
        }
        if (!md.trim()) {
            toast.fail("请对本商品的详情做一定的说明!");
            return;
        }
        // 把图片的原始宽高添加到图片信息里
        let goodsImages = imgArr.map((item) => {
            let img = new Image();
            img.src = item.img;
            item.width = img.width;
            item.height = img.height;
            return item;
        });
        onSellGoodsAction(
            {
                goodsName,
                cateTag,
                goodsImages: goodsImages,
                brand,
                oldDegree: parseInt(oldDegree),
                price: parseFloat(price),
                isAcceptCutPrice,
                billImg,
                goodsDetails: md,
            },
            navigate
        );
    };

    return (
        <div className={styles.sell_wrap}>
            <Nav />
            <div className={styles.sell_main}>
                <label htmlFor="goodsName">
                    商品名称：
                    <input
                        type="text"
                        id="goodsName"
                        required
                        minLength={1}
                        maxLength={20}
                        value={goodsName}
                        onChange={(e) => setGoodsName(e.target.value)}
                    />
                </label>
                <br />
                <br />
                <label htmlFor="cate">
                    商品分类：
                    <select
                        name="cate"
                        id="cate"
                        value={cateTag}
                        onChange={(e) => {
                            setCateTag(e.target.value);
                        }}
                    >
                        <option
                            value="---选择分类---"
                            defaultChecked
                            style={{ color: "gray" }}
                        >
                            ---选择分类---
                        </option>
                        {[
                            "电子产品",
                            "家用电器",
                            "办公用品",
                            "学习用品",
                            "穿搭相关",
                            "零食百货",
                        ].map((item, index) => (
                            <option key={index} value={item}>
                                {item}
                            </option>
                        ))}
                    </select>
                </label>
                <br />
                <div className={styles.upload_imgs}>
                    <div className={styles.p1}>
                        商品图片链接<span>(可添加多张)</span>：
                        <div
                            className={styles.addImg}
                            onClick={() => {
                                if (imgArr.length > 4) {
                                    toast.info("最多上传5张");
                                    return;
                                }
                                let _imgArr = [...imgArr];
                                _imgArr.push({
                                    id: Date.now().toString(),
                                    img: "",
                                });
                                setImgArr(_imgArr);
                            }}
                        >
                            +
                        </div>
                    </div>
                    <ul className={styles.goods_images_ul}>
                        {imgArr.map((item, index) => (
                            <li key={item.id}>
                                <span>{index + 1}. </span>
                                <input
                                    type="text"
                                    value={item.img}
                                    onChange={(e) => {
                                        let _imgArr = [...imgArr];
                                        _imgArr[index].img = e.target.value;
                                        setImgArr(_imgArr);
                                    }}
                                />
                                {item.img && (
                                    <div className={styles.show_goods_img}>
                                        {/* <AvatarEditor
                    id={`editor${index + 1}`}
                    image={item.img}
                    width={460}
                    height={280}
                    border={50}
                    color={[255, 255, 255, 0.6]} // RGBA
                    scale={1.2}
                    rotate={0}
                    crossOrigin="anonymous"
                  /> */}
                                        <img src={item.img} alt="" />
                                    </div>
                                )}
                                <div
                                    className={styles.delImg}
                                    onClick={() => {
                                        let _imgArr = [...imgArr];
                                        _imgArr.splice(index, 1);
                                        setImgArr(_imgArr);
                                    }}
                                >
                                    -
                                </div>
                            </li>
                        ))}
                    </ul>
                </div>
                <br />
                <label htmlFor="brand">
                    品牌：
                    <input
                        type="text"
                        required
                        id="brand"
                        placeholder="商品是什么牌子的？"
                        value={brand}
                        onChange={(e) => {
                            setBrand(e.target.value);
                        }}
                    />
                </label>
                <br />
                <br />
                <label htmlFor="oldDegree">
                    成色：
                    <input
                        type="number"
                        id="oldDegree"
                        required
                        placeholder="填写数字1~10"
                        value={oldDegree}
                        onChange={(e) => {
                            setOldDegree(e.target.value);
                        }}
                    />{" "}
                    成新
                </label>
                <br />
                <br />
                <label htmlFor="price">
                    定价：
                    <input
                        type="number"
                        id="price"
                        required
                        value={price}
                        onChange={(e) => {
                            const v = e.target.value;
                            if (moneyReg.test(v) || v === "") {
                                setPrice(e.target.value);
                                setActualMoney(
                                    actualGmoney(Number(e.target.value))
                                );
                            }
                        }}
                    />{" "}
                    G币
                </label>
                <br />
                <p className={styles.p2}>
                    <strong>·</strong> 售出后将获得{actualMoney}G币
                </p>
                <br />
                <label htmlFor="isAcceptCutPrice">
                    是否接收议价：
                    <input
                        type="radio"
                        name="isAcceptCutPrice"
                        className={styles.isAcceptCutPrice}
                        checked={isAcceptCutPrice}
                        value={true}
                        onChange={(e) => {
                            setIsAcceptCutPrice(true);
                        }}
                    />{" "}
                    是 &emsp;
                    <input
                        type="radio"
                        name="isAcceptCutPrice"
                        className={styles.isAcceptCutPrice}
                        checked={!isAcceptCutPrice}
                        value={false}
                        onChange={(e) => {
                            setIsAcceptCutPrice(false);
                        }}
                    />{" "}
                    否
                </label>
                <br />
                <div className={styles.bill_img}>
                    <p className={styles.p3}>发票图片链接：</p>
                    <input
                        type="text"
                        required
                        value={billImg}
                        onChange={(e) => {
                            setBillImg(e.target.value);
                        }}
                    />
                    <div className={styles.show_bill_img}>
                        {<img src={billImg} alt="" />}
                    </div>
                </div>
                <div className={styles.details}>
                    <p className={styles.p4}>商品详情：</p>
                    <MDEditor
                        height={320}
                        value={md}
                        onChange={setMd}
                        previewOptions={{
                            rehypePlugins: [[rehypeSanitize]],
                        }}
                        visibleDragbar={false}
                    />
                </div>
                <input
                    type="button"
                    value="上架"
                    className={styles.put_on_sale}
                    onClick={() => {
                        putOnSale();
                    }}
                />
            </div>
            <PortalContainer />
        </div>
    );
};

export default connect((state) => ({ isOnSell: state.onSellGoodsReducer }), {
    onSellGoodsAction,
})(Sell);
